package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {
    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelContentMapper contentMapper;

    public void updateState(Long id, Integer state) {
        Travel travel = new Travel();
        travel.setId(id);
        travel.setState(state);
        if (state == Travel.STATE_RELEASE) {
            //需要设置发布时间
            travel.setReleaseTime(new Date());
        }
        travelMapper.changeState(travel);
        //如果当前是下架,则删除当前游记的推荐 where travel_id = #{id}
    }

    public TravelContent getContent(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    public Travel get(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    public PageInfo<Travel> queryTravels(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Travel> list = travelMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public void saveOrUpdate(Travel entity) {
        Date d = new Date();
        entity.setLastUpdateTime(d); //设置最后更新时间
        //获取当前游记的内容
        TravelContent travelContent = entity.getTravelContent();
        if (entity.getId() == null) {
            //是否有手动录入的数据
            //创建时间
            entity.setCreateTime(d);
            travelMapper.insert(entity);
            //同步保存文章的内容,设置主键关联
            travelContent.setId(entity.getId());
            contentMapper.insert(travelContent);
        } else {
            travelMapper.updateByPrimaryKey(entity);
            //同步更新游记内容
            travelContent.setId(entity.getId());
            contentMapper.updateByPrimaryKey(travelContent);
        }
    }
}
